const bcryptjs = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { result } =require('../config/result')
const { JWT_SECRET } = require('../config/config.dev')
const { verifyMobileRepeat,verifyUserNameeRepeat} = require('../db/user')

//校验用户和手机号是不是重复
const userNameMobileValidator = async(ctx,next)=>{
  const {id,username,mobile }= ctx.request.body;
  const ret =  await verifyUserNameeRepeat(id,username) 
  if(ret && ret.length>0){
    result.success = false 
    result.message = "登录名已使用"
    result.data = null
    ctx.body = result
    return 
  } 
  const ret1 =  await verifyMobileRepeat(id,mobile) 
  if(ret1 && ret1.length>0){
    result.success = false 
    result.message = "手机号已注册"
    result.data = null
    ctx.body = result
    return 
  } 
  await next()
}

const userValidator = async(ctx,next)=>{
  const {username,password }= ctx.request.body;
  // 判断用户名和密码是否为空
  if(!username || !password ){
    result.success=false
    result.message='用户名或密码不能为空。'
    result.data=null
    ctx.body = result
    return
  }
  await next()
}

const pwdCrypted = async(ctx,next)=>{
  const {oldpwd,newpwd,id }= ctx.request.body;
  var salt = bcryptjs.genSaltSync(10);
  var hash = bcryptjs.hashSync(newpwd, salt);
  ctx.request.body.newpwd = hash;
  await next()
}

const authToken = async(ctx,next)=>{
  try{
    const token = ctx.request.header.authorization.split(' ')[1]
    const  userinfo = jwt.verify(token, JWT_SECRET);
    ctx.state.user = userinfo
    await next()
  }catch(e){
    ctx.app.emit('error',e.message,ctx)
  }
}

module.exports = {
  userValidator,
  pwdCrypted,
  authToken,
  userNameMobileValidator
}